package cn.hh.bean;

import cn.hh.bean.enumbean.ResultCodeEnum;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author huangh
 * @date 2021/09/28
 * @Description:
 */
@Data
public class PageResult<T> implements Serializable {

    private Integer code;
    private String message;
    private List<T> data;
    // 新增和分页相关的三个字段
    private Long page;
    private Long pageSize;
    private Long total;

    private PageResult(List<T> data, long page, long pageSize, long total) {
        this.code = ResultCodeEnum.SUCCESS.getCode();
        this.message = ResultCodeEnum.SUCCESS.getMessage();
        this.data = data;
        this.page = page;
        this.pageSize = pageSize;
        this.total = total;
    }

    /**
     * 成功实体，传入一个page对象
     *
     * @param page
     */
    public static <T> PageResult<T> success(Page<T> page) {
        if (page != null) {
            //这里我用的是mybatisplus是插件
            //案例是PageHelper，此时针对PageHelper的分页可以封装一个专门的PageResult：
            //return new PageResult<>(page.getResult(), page.getPageNum(), page.getPageSize(), page.getTotal());
            return new PageResult<T>(page.getRecords(), page.getCurrent(), page.getSize(), page.getTotal());
        } else {
            return new PageResult<>(new ArrayList<T>(), 0, 1, 10L);
        }
    }
}
